package com.lemner.ke.view;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lemner.ke.util.EscapeUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 富文本-webview
 *
 * @author 杨烨
 * @date 2018/9/13
 */
public class RichTextView extends WebView {
    private String content;

    public RichTextView(Context context) {
        super(context);
    }

    public RichTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RichTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RichTextView(Context context, String content) {
        super(context);
        this.content = content;
        setRichText();
    }

    public void setContent(String content) {
        this.content = content;
        setRichText();
    }

    public void setRichText() {
        getSettings().setJavaScriptEnabled(true);
        getSettings().setBuiltInZoomControls(true);
        getSettings().setDisplayZoomControls(false);
        setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        setWebChromeClient(new WebChromeClient());
        setWebViewClient(new WebViewClient());
        getSettings().setDefaultTextEncodingName("UTF-8");
        getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getSettings().setMixedContentMode(getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
        String content = EscapeUtil.htmlEscape(this.content);
        loadDataWithBaseURL(null, getNewContent(content), "text/html", "UTF-8", null);
    }

    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            if (element.className() != null && element.className().length() > 0)
                element.attr("width", "100%").attr("height", "auto");
        }
        return doc.toString();
    }
}
